import * as fs from 'fs/promises';
import * as path from 'path';

export class DiagramRulesManager {
  private rulesPath: string;
  private versionManagePath: string;

  constructor() {
    // 使用相对于项目根目录的路径
    const projectRoot = path.resolve(path.dirname(new URL(import.meta.url).pathname), '..');
    this.rulesPath = path.join(projectRoot, 'docs', 'drawio-rules-v2.md');
    this.versionManagePath = path.join(projectRoot, 'docs', 'version_manage.md');
  }

  async loadRules(ruleType: string = 'all') {
    try {
      const rulesContent = await fs.readFile(this.rulesPath, 'utf-8');
      const versionContent = await fs.readFile(this.versionManagePath, 'utf-8');

      let content = '';
      
      switch (ruleType) {
        case 'naming':
          content = this.extractNamingRules(rulesContent, versionContent);
          break;
        case 'styling':
          content = this.extractStylingRules(rulesContent);
          break;
        case 'versioning':
          content = this.extractVersioningRules(versionContent);
          break;
        case 'all':
        default:
          content = this.formatAllRules(rulesContent, versionContent);
          break;
      }

      return {
        content: [
          {
            type: 'text',
            text: `# Draw.io 绘图规范加载完成 (v2.0)\n\n${content}\n\n## 🎯 重要更新说明\n\n本项目已更新至 **v2.0 绘图规范**，基于 drawio_mcp_sequence_v1.0_20250823.drawio 的优秀实践总结。\n\n## 📋 使用指导\n\n1. **时序图绘制**：\n   - 先生成Mermaid时序图语法\n   - 使用 convert_mermaid_to_drawio_llm 工具转换\n   - 严格遵循线宽1px规范，避免粗线条\n   - 正确处理自环消息的弯曲路径\n\n2. **流程图绘制**：\n   - 根据新规范生成符合标准的Draw.io流程图\n   - 使用标准颜色体系和组件样式\n   - 保持一致的间距和对齐\n\n3. **文件管理**：\n   - 统一存放在 ./drawio 目录下\n   - 按照新的命名规范：[模块名]_[图表类型]_v[版本号]_[日期].drawio\n\n4. **样式规范**：\n   - 参与者：#dae8fc填充 + #6c8ebf边框\n   - 线条：统一1px宽度，避免粗线\n   - 字体：按层级使用18px/12px/10px\n\n## ⚠️ 关键改进\n\n- **线条优化**：统一使用1px线宽，提升视觉效果\n- **自环处理**：新增自环消息的正确绘制方法\n- **颜色统一**：基于0823版本的优秀配色方案\n- **布局规范**：精确的间距和对齐标准\n\n现在您可以开始绘制符合新规范的图表了！`
          }
        ]
      };
    } catch (error) {
      return {
        content: [
          {
            type: 'text',
            text: `加载规则失败: ${error instanceof Error ? error.message : String(error)}`
          }
        ]
      };
    }
  }

  private extractNamingRules(rulesContent: string, versionContent: string): string {
    const namingSection = this.extractSection(rulesContent, '## 文件命名');
    const versionNaming = this.extractSection(versionContent, '版本命名规范');
    
    return `## 文件命名规范\n\n${namingSection}\n\n${versionNaming}`;
  }

  private extractStylingRules(rulesContent: string): string {
    const designSection = this.extractSection(rulesContent, '## 设计规范');
    const styleSection = this.extractSection(rulesContent, '## 标准样式');
    
    return `## 样式设计规范\n\n${designSection}\n\n${styleSection}`;
  }

  private extractVersioningRules(versionContent: string): string {
    return `## 版本管理规范\n\n${versionContent}`;
  }

  private formatAllRules(rulesContent: string, versionContent: string): string {
    return `## 完整Draw.io绘图规范\n\n### 绘图规则\n${rulesContent}\n\n### 版本管理\n${versionContent}`;
  }

  private extractSection(content: string, sectionTitle: string): string {
    const lines = content.split('\n');
    const startIndex = lines.findIndex(line => line.includes(sectionTitle));
    
    if (startIndex === -1) return '';
    
    let endIndex = lines.length;
    for (let i = startIndex + 1; i < lines.length; i++) {
      if (lines[i].startsWith('## ') && !lines[i].includes(sectionTitle)) {
        endIndex = i;
        break;
      }
    }
    
    return lines.slice(startIndex, endIndex).join('\n');
  }

  async validateSpecs(diagramDescription: string, filename?: string): Promise<any> {
    try {
      const issues: string[] = [];
      
      // 验证文件名格式
      if (filename) {
        const namePattern = /^[a-zA-Z0-9_]+_(flowchart|architecture|sequence|class|component)_v\d+\.\d+_\d{8}\.drawio$/;
        if (!namePattern.test(filename)) {
          issues.push('文件名格式不符合规范。正确格式：[模块名]_[图表类型]_v[版本号]_[日期].drawio');
        }
      }
      
      // 验证图表描述
      if (!diagramDescription || diagramDescription.trim().length < 10) {
        issues.push('图表描述过于简单，建议提供更详细的描述');
      }
      
      // 检查是否包含必要的组件描述
      const requiredElements = ['用户', '系统', '流程', '数据'];
      const hasRequiredElements = requiredElements.some(element => 
        diagramDescription.includes(element)
      );
      
      if (!hasRequiredElements) {
        issues.push('建议在描述中包含用户、系统、流程或数据等关键元素');
      }
      
      const isValid = issues.length === 0;
      
      return {
        content: [
          {
            type: 'text',
            text: `## 图表规范验证结果\n\n**验证状态**: ${isValid ? '✅ 通过' : '❌ 需要改进'}\n\n${
              issues.length > 0 
                ? `**发现的问题**:\n${issues.map(issue => `- ${issue}`).join('\n')}\n\n**建议**: 请根据上述问题调整图表描述或文件名。`
                : '**结果**: 图表描述符合规范要求，可以开始绘制。'
            }`
          }
        ]
      };
    } catch (error) {
      return {
        content: [
          {
            type: 'text',
            text: `验证过程出错: ${error instanceof Error ? error.message : String(error)}`
          }
        ]
      };
    }
  }
}
